/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package persistence.dao.mysql;

import persistence.entites.Type;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import persistence.entites.POI;

/**
 *
 * @author Anthony
 */
public class TypeDAO extends MySQLDAO<Type> {

    public TypeDAO(EntityManager em, Class<?> classe) {
        super(em, classe);
    }

    @Override
    public boolean insert(Type object) {
        Type type = this.findById(object.getId());
        if(type == null){
            return super.insert(object);
        }
        if (type.getName().equals(object.getName())) {
            return false;
        }
        return false;
    }

    public Type findByName(String name) {
        String className = classe.getSimpleName();
        String textQuery = "select o from " + className + " as o where o.name = :objectname";
        Query query = em.createQuery(textQuery);
        query.setParameter("objectname", name);
        try{
            return (Type) query.getSingleResult();
        }
        catch(NoResultException e){
            return null;
        }
    }

    public List<Type> findAllSuperTypes(String name){
        String className = classe.getSimpleName();
        String textQuery = "select o from " + className + " as o where o.name <> :objectname";
        Query query = em.createQuery(textQuery);
        query.setParameter("objectname", name);
        try{
            return query.getResultList();
        }
        catch(NoResultException e){
            return null;
        }
    }

    @Override
    public boolean delete(Type object) {
        for(POI poi : object.getPois()){
            poi.setTag(null);
        }
        return super.delete(object);
    }
}
